package com.example.adv_android;

import android.app.ActivityManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import androidx.activity.EdgeToEdge;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.IOException;
import java.io.PrintWriter;

public class MainActivity extends AppCompatActivity {

    public Handler handler = new Handler(Looper.getMainLooper());

    int[] videoIds = {0, R.id.video1, R.id.video2, R.id.video3, R.id.video4, R.id.video5, R.id.video6, R.id.video7, R.id.video8};
    int[] priceIds = {0, R.id.tv_price1, R.id.tv_price2, R.id.tv_price3, R.id.tv_price4, R.id.tv_price5, R.id.tv_price6, R.id.tv_price7, R.id.tv_price8};


    MediaPlayer[] players = new MediaPlayer[9];
    SurfaceView surface;
    SurfaceHolder surfaceHolder;

    private BroadcastReceiver usbReceiver;

    private ExitDialog exitDialog;

    String[] priceArr;

    //本地视频路径
    String path = Environment.getExternalStorageDirectory().getPath() + "/adv/sp";
    //usb视频路径
    String usbpath = "/mnt/usb_storage/udisk/adv/sp";

    //总视频数量
    final int total_video = 8;


    @Subscribe(threadMode = ThreadMode.MAIN_ORDERED)
    public void onMessageEvent(EventMessage event) {
        String price = "￥" + event.getPrice() + " ";
        if (priceArr[event.getIndex() - 1].equals(price)) return;
        priceArr[event.getIndex() - 1] = price;
        StringBuilder sb = new StringBuilder();
        for (int i = 1; i <= total_video; i++) {
            sb.append(priceArr[i - 1]);
            if (i != total_video) sb.append(",");
        }
        Store.put(Store.PricesKey, sb.toString());

        TextView textView = findViewById(priceIds[event.getIndex()]);
        textView.setText(price);
        // 隐藏底部导航栏
        getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_HIDE_NAVIGATION);
    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EdgeToEdge.enable(this);
        setContentView(R.layout.activity_main);
        EventBus.getDefault().register(this);


        String prices = Store.get(Store.PricesKey);
        if (Store.get(Store.PricesKey).isEmpty()) {
            priceArr = new String[total_video];
            StringBuilder sb = new StringBuilder();
            for (int i = 1; i <= total_video; i++) {
                priceArr[i - 1] = "￥35 ";
                sb.append(priceArr[i - 1]);
                if (i != total_video) sb.append(",");
            }
            Store.put(Store.PricesKey, sb.toString());
        } else {
            priceArr = prices.split(",");
            int length = priceArr.length;
            if (length > total_video) length = total_video;
            for (int i = 1; i <= length; i++) {
                TextView textView = findViewById(priceIds[i]);

                textView.setText(priceArr[i - 1]);
            }
        }

        //修改价格对话框
        exitDialog = new ExitDialog(this);

        // 隐藏底部导航栏
        getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_HIDE_NAVIGATION);

        // 注册USB BroadcastReceiver
        usbReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                String action = intent.getAction();
                if (Intent.ACTION_MEDIA_MOUNTED.equals(action)) {
                    // USB存储设备已插入
                    Toast.makeText(context, "USB设备已插入", Toast.LENGTH_SHORT).show();
                    String usbPath = intent.getData().getPath();
//                    Log.d("TAG", "onReceive: " + usbPath);


                    //重新加载视频
                    resetPlayer();

                } else if (Intent.ACTION_MEDIA_UNMOUNTED.equals(action)) {
                    // USB存储设备已移除
                    Toast.makeText(context, "USB设备已移除", Toast.LENGTH_SHORT).show();
                }
            }
        };


        IntentFilter usbIntentFilter = new IntentFilter();
        usbIntentFilter.addAction(Intent.ACTION_MEDIA_MOUNTED);
        usbIntentFilter.addAction(Intent.ACTION_MEDIA_UNMOUNTED);
        usbIntentFilter.addDataScheme("file");
        registerReceiver(usbReceiver, usbIntentFilter);


        TextView tv_t1 = findViewById(R.id.tv_t1);
        tv_t1.setOnLongClickListener(v -> {
            finish();
            return false;
        });

        for (int i = 1; i <= total_video; i++) {
            int finalI = i;
            findViewById(priceIds[i]).setOnClickListener(v -> exitDialog.showDialog(finalI));
        }


        TextView tv_t2 = findViewById(R.id.tv_t2);
        TextView tv_t3 = findViewById(R.id.tv_t3);
        new Thread(() -> {
            int k = 0;
            for (; ; ) {
                try {
                    Thread.sleep(5000);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }

                ActivityManager activityManager1 = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
                ActivityManager.MemoryInfo memoryInfo1 = new ActivityManager.MemoryInfo();
                activityManager1.getMemoryInfo(memoryInfo1);

//                Log.d("TAG", "onCreate1: 系统可用内存" + memoryInfo1.availMem / 1024 / 1024 + "M");
                k++;
                int j = k;
                handler.post(() -> {
                    tv_t2.setText(memoryInfo1.availMem / 1024 / 1024 + "M");
                    tv_t3.setText(memoryInfo1.totalMem / 1024 / 1024 + "M" + " " + j);

                });
                if (j == 10) k = 0;
            }
        }).start();


        closeLogd();

    }

    //关闭logd日志服务。防止logcat占用内存过大
    private void closeLogd() {
        Process runtime;//su：管理员身份运行，提取root权限
        try {
            runtime = Runtime.getRuntime().exec("su");
            //前提是安卓系统本身root过。不然无法安装
            PrintWriter pw = new PrintWriter(runtime.getOutputStream());
            pw.println("stop logd");
            pw.flush();
            pw.close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

    }

    private void initView() {
        for (int i = 1; i <= total_video; i++) {
            surface = findViewById(videoIds[i]);
            surfaceHolder = surface.getHolder(); // SurfaceHolder是SurfaceView的控制接口
            int k = i;
            surfaceHolder.addCallback(new SurfaceHolder.Callback() {
                @Override
                public void surfaceCreated(@NonNull SurfaceHolder surfaceHolder) {
                    players[k] = new MediaPlayer(); // 必须在surface创建后才能初始化MediaPlayer,否则不会显示图像
                    players[k].setDisplay(surfaceHolder);
                    // 设置显示视频显示在SurfaceView上
                    try {
                        players[k].setDataSource(usbpath + k + ".mp4");
                        players[k].setLooping(true);//设置循环播放
                        players[k].prepare();
                        // 设置音量为零，静音
                        players[k].setVolume(0.0f, 0.0f);
                        players[k].start();
                    } catch (Exception e) {
                        e.printStackTrace();
//                        Log.d("TAG", "surfaceCreated: " + e.getMessage());
                    }
                }

                @Override
                public void surfaceChanged(@NonNull SurfaceHolder surfaceHolder, int i, int i1, int i2) {
                }

                @Override
                public void surfaceDestroyed(@NonNull SurfaceHolder surfaceHolder) {
                    if (players[k] != null) {
                        players[k].stop(); // 停止播放
                        players[k].release(); // 释放MediaPlayer资源
                        players[k] = null; // 设置为null，避免后续的空指针异常
                    }
                }
            }); // 因为这个类实现了SurfaceHolder.Callback接口，所以回调参数直接this
        }
    }


    /*ExoPlayer*/
//    private void initExoPlayer(Context mContext){
//        for (int i = 1; i <= 8; i++) {
//            PlayerView playerView = findViewById(videoIds[i]);
//            SimpleExoPlayer player = new SimpleExoPlayer.Builder(mContext).build();
//            playerView.setPlayer(player);
//            String videoUrl = Environment.getExternalStorageDirectory().getPath() + "/adv/sp" + i + ".mp4";
//            MediaItem mediaItem = MediaItem.fromUri(videoUrl);
//            player.setMediaItem(mediaItem);
//            player.setRepeatMode(Player.REPEAT_MODE_ALL);
//            player.prepare();
//            player.setPlayWhenReady(true);
//            player.play();
//        }
//    }

    //重新加载视频
    private void resetPlayer() {
        for (int i = 1; i <= total_video; i++) {
            if (players[i] != null) {
                players[i].reset();
            }

            try {
                players[i].setDataSource(usbpath + i + ".mp4");
                players[i].setLooping(true);//设置循环播放
                players[i].prepare();
                // 设置音量为零，静音
                players[i].setVolume(0.0f, 0.0f);
                players[i].start();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }


    @Override
    protected void onStart() {
        super.onStart();
        initView();
    }

    @Override
    protected void onStop() {
        super.onStop();
        releasePlayer();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(usbReceiver);
        releasePlayer();
        EventBus.getDefault().unregister(this);
    }

    //释放播放器资源
    private void releasePlayer() {
        for (int i = 1; i <= total_video; i++) {
            if (players[i] != null) {
                players[i].release();
                players[i] = null;
            }
        }
    }

}